const path = require('path');
const fs = require('fs');

const DATA_DIR = path.join(process.cwd(), 'excel', '06-21');
const DB_PATH = path.join(process.cwd(), 'data', 'json-database.json');

// 手动解析CSV行
function parseCSVLine(line) {
  const result = [];
  let current = '';
  let inQuotes = false;
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i];
    
    if (char === '"') {
      inQuotes = !inQuotes;
    } else if (char === ',' && !inQuotes) {
      result.push(current.trim());
      current = '';
    } else {
      current += char;
    }
  }
  
  result.push(current.trim());
  return result;
}

async function simpleImport() {
  try {
    console.log('开始简单导入数据...');
    
    // 读取当前数据库
    const dbContent = fs.readFileSync(DB_PATH, 'utf-8');
    const db = JSON.parse(dbContent);
    
    const DEVICE_TABLE_FILES = [
      '设备表-配管专业.csv',
      '设备表-电气专业.csv',
      '设备表-暖通专业.csv',
      '设备表-通信专业.csv',
      '设备表-仪表专业.csv',
    ];
    
    // 为每个专业维护独立的设备计数器
    const deviceCounters = {
      '配管专业': 1,
      '电气专业': 1,
      '暖通专业': 1,
      '通信专业': 1,
      '仪表专业': 1
    };
    
    let totalDevices = 0;
    
    for (const filename of DEVICE_TABLE_FILES) {
      const specialty = filename.replace('设备表-', '').replace('.csv', '');
      const filePath = path.join(DATA_DIR, filename);
      
      console.log(`\n处理文件: ${filename} (${specialty})`);
      
      const content = fs.readFileSync(filePath, 'utf-8');
      const lines = content.split('\n').filter(line => line.trim());
      
      if (lines.length === 0) {
        console.log('文件为空，跳过');
        continue;
      }
      
      // 第一行是表头
      const headers = parseCSVLine(lines[0]);
      console.log('表头:', headers);
      
      // 找到设备名称列的索引
      const nameIndex = headers.findIndex(h => h.includes('设备表及材料表中的实体对象名称'));
      if (nameIndex === -1) {
        console.log('未找到设备名称列，跳过文件');
        continue;
      }
      
      console.log(`设备名称列索引: ${nameIndex}`);
      
      // 处理数据行
      for (let i = 1; i < lines.length; i++) {
        const values = parseCSVLine(lines[i]);
        
        if (values.length <= nameIndex || !values[nameIndex] || values[nameIndex].trim() === '') {
          continue;
        }
        
        const deviceName = values[nameIndex].trim();
        console.log(`第${i}行 - 设备名称: "${deviceName}"`);
        
        // 生成唯一的设备ID
        const specialtyPrefix = specialty === '配管专业' ? 'PP' :
                              specialty === '电气专业' ? 'EL' :
                              specialty === '暖通专业' ? 'HV' :
                              specialty === '通信专业' ? 'CM' :
                              'IN'; // 仪表专业
        
        const deviceNumber = deviceCounters[specialty].toString().padStart(4, '0');
        const uniqueDeviceId = `${specialtyPrefix}-${deviceNumber}`;
        
        const deviceData = {
          id: uniqueDeviceId,
          name: deviceName,
          classificationName: values[headers.findIndex(h => h.includes('对应的对象分类标准中的中文名称'))] || '',
          序号: values[headers.findIndex(h => h.includes('序号'))] || '',
          classificationCode: values[headers.findIndex(h => h.includes('分类码'))] || '',
          specialty: specialty,
          namingTableId: values[headers.findIndex(h => h.includes('对象命名'))] || '',
          positionTableId: values[headers.findIndex(h => h.includes('位置信息'))] || '',
          baseParamsTableId: values[headers.findIndex(h => h.includes('基础参数'))] || '',
          techSpecTableId: values[headers.findIndex(h => h.includes('技术规格书'))] || '',
          备注: values[headers.findIndex(h => h.includes('备注'))] || ''
        };
        
        console.log(`  -> 添加设备: ${deviceData.name} (${uniqueDeviceId})`);
        db.devices.push(deviceData);
        totalDevices++;
        deviceCounters[specialty]++;
      }
    }
    
    // 保存更新后的数据库
    fs.writeFileSync(DB_PATH, JSON.stringify(db, null, 2));
    
    console.log(`\n成功导入 ${totalDevices} 个设备！`);
    
    // 统计各专业设备数量
    const stats = {};
    db.devices.forEach(device => {
      stats[device.specialty] = (stats[device.specialty] || 0) + 1;
    });
    
    console.log('\n各专业设备统计:');
    Object.entries(stats).forEach(([specialty, count]) => {
      console.log(`${specialty}: ${count} 个设备`);
    });
    
  } catch (error) {
    console.error('导入失败:', error);
  }
}

// 执行导入
simpleImport(); 